/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cashforward.ui.scenario;

import com.jidesoft.swing.DefaultOverlayable;
import com.jidesoft.swing.OverlayableUtils;
import com.jidesoft.swing.StyledLabelBuilder;
import java.awt.BorderLayout;
import org.cashforward.ui.UIContext;
import java.io.Serializable;
import java.util.Collection;
import java.util.logging.Logger;
import org.cashforward.model.Scenario;
import org.cashforward.ui.task.PaymentFilter;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

/**
 * Shows the Scenario graphs and controls.
 */
final class ScenarioTopComponent extends TopComponent {

    private static ScenarioTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private DefaultOverlayable chartOverlay;
    private Lookup.Result filterNotifier =
            UIContext.getDefault().lookupResult(PaymentFilter.class);
    private Lookup.Result scenarioNotifier =
            UIContext.getDefault().lookupResult(Scenario.class);
    private PaymentFilter paymentFilter =
            UIContext.getDefault().getPaymentFilter();
    private static final String PREFERRED_ID = "ScenarioTopComponent";

    private ScenarioTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(ScenarioTopComponent.class, "CTL_ScenarioTopComponent"));
        setToolTipText(NbBundle.getMessage(ScenarioTopComponent.class, "HINT_ScenarioTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));

        scenarioPanel.setPayments(UIContext.getDefault().getPayments());
        scenarioPanel.setPaymentFilter(paymentFilter);

        filterNotifier.addLookupListener(new LookupListener() {

            public void resultChanged(LookupEvent event) {
                Lookup.Result r = (Lookup.Result) event.getSource();
                Collection c = r.allInstances();
                if (!c.isEmpty()) {
                    PaymentFilter filter =
                            (PaymentFilter) c.iterator().next();
                    if (filter.getDateEnd() != null) {
                        scenarioPanel.setPaymentFilter(paymentFilter);
                    }
                }
                refreshOverlay();
            }
        });

        setupOverlay();
    }

    private void setupOverlay() {
        remove(scenarioPanel);
        chartOverlay = new DefaultOverlayable(scenarioPanel);

        OverlayLookupListener oll = new OverlayLookupListener();
        scenarioNotifier.addLookupListener(oll);
        
        chartOverlay.addOverlayComponent(
                StyledLabelBuilder.createStyledLabel("{No Cashflow available." +
                "Add Payments to see how it affects the Cashflow.  :f:gray}"));

        add(chartOverlay,BorderLayout.CENTER);
        
        refreshOverlay();
    }
    
    private void refreshOverlay() {
        boolean scenarioSelected =
                UIContext.getDefault().getSelectedScenarios().size() > 0;
        boolean paymentsInTable =
                UIContext.getDefault().getPayments().size() > 0;

        if (scenarioSelected) {
            if (!paymentsInTable) { //show no payments message
                scenarioPanel.setVisible(false);
                chartOverlay.getOverlayComponents()[0].setVisible(true);
                //chartOverlay.getOverlayComponents()[1].setVisible(false);
                UIContext.getDefault().clearPayment();
            } else { //just show the table
                scenarioPanel.setVisible(true);
                chartOverlay.getOverlayComponents()[0].setVisible(false);
                //chartOverlay.getOverlayComponents()[1].setVisible(false);
            }
        } else { //show select scenario message
            scenarioPanel.setVisible(false);//for now
            chartOverlay.getOverlayComponents()[0].setVisible(true);
            UIContext.getDefault().clearPayment();
        }

        OverlayableUtils.repaintOverlayable(chartOverlay);
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scenarioPanel = new org.cashforward.ui.scenario.ScenarioPanel();

        setLayout(new java.awt.BorderLayout());
        add(scenarioPanel, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.cashforward.ui.scenario.ScenarioPanel scenarioPanel;
    // End of variables declaration//GEN-END:variables

    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized ScenarioTopComponent getDefault() {
        if (instance == null) {
            instance = new ScenarioTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the ScenarioTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ScenarioTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(ScenarioTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ScenarioTopComponent) {
            return (ScenarioTopComponent) win;
        }
        Logger.getLogger(ScenarioTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    /** replaces this in object stream */
    @Override
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return ScenarioTopComponent.getDefault();
        }
    }

    class OverlayLookupListener implements LookupListener {

        public void resultChanged(LookupEvent arg0) {
            refreshOverlay();
        }
    }
}
